/**
 * Copyright (C), 2001-2023, www.bosssof.com.cn
 * FileName: RedisTemplateTestController
 * Author: Administrator
 * Date: 2023-05-24 22:36:13
 * Description:
 * <p>
 * History:
 * <author> Administrator
 * <time> 2023-05-24 22:36:13
 * <version> 1.0.0
 * <desc> 版本描述
 */
package com.bosssoft.quickstart.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bosssoft.quickstart.demo.dao.entity.User;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @ClassName: RedisTemplateTestController
 * @Description:
 * abel.zhan 2023/05/24 用于测试String和Hash方式下的对象存储
 * @Author: Administrator
 * @Date: 2023-05-24 22:36
 **/
@Slf4j
@RestController
@RequestMapping(value = "demo/redis/for/")
public class RedisTemplateTestController {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @RequestMapping("set/value")
    public void testOpsForValue(){
        for(int i=0;i<10;i++){
            User user=new User("name1"+i,"id"+i,new Date());
            redisTemplate.opsForValue().set("user:id:"+i,user);
        }
    }


    @ResponseBody
    @RequestMapping("get/value")
    public List<User> testOpsForValue2(){
        List<User> userList=new ArrayList<>();
        for(int i=0;i<10;i++){
          String userString= JSON.toJSONString(redisTemplate.opsForValue().get("user:id:"+i));
          log.info(userString);
          User user=JSON.parseObject(
                  userString,
                          User.class) ;

          userList.add(user);
        }
        return userList;
    }


    @RequestMapping("set/hash")
    public void testOpsForHash(){
        Map<String,User>  userMap=new HashMap<>();
        for(int i=1;i<10;i++){
            for(int j=1;j<100;j++){
                userMap.put(new Long(j).toString(),new User("name"+i,"id"+j,new Date(0)));
            }
            redisTemplate.opsForHash().putAll("test:role:id:"+i,userMap);
        }
    }

    @RequestMapping("get/hash/{id}")
    public String testOpsForHash2(@PathVariable("id") Long id){
         Map userMap= redisTemplate.opsForHash().entries("test:role:id:"+id);
        Collection collection= userMap.values();
        return JSONObject.toJSONString(collection);
    }


}
